package com.yds.bluetooth.views

import android.annotation.SuppressLint
import android.bluetooth.BluetoothDevice
import android.content.Context
import android.graphics.Color
import android.util.AttributeSet
import android.util.Log
import kotlin.jvm.JvmOverloads
import androidx.appcompat.widget.LinearLayoutCompat
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import com.yds.bluetooth.R
import androidx.recyclerview.widget.RecyclerView
import com.yds.bluetooth.YDSBluetoothHelper
import com.yds.bluetooth.utils.YDSDelayHelper

@Suppress("unused")
class BluetoothDeviceView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : LinearLayoutCompat(context, attrs, defStyleAttr),
    OnBluetoothFunctionsListener, OnBluetoothViewFunctionsListener {

    private val tag = "YDS蓝牙"

    private var mRecyclerViewBluetooth: RecyclerView? = null
    private var mBluetoothAdapter: YDSRecyclerViewOAdapter<BluetoothDevice>? = null
    private var selectedDevice: BluetoothDevice? = null
    private val mListBluetoothDevices = mutableListOf<BluetoothDevice>()
    private var isDeviceConnecting = false
    private var connectDeviceAddress = ""

    init {
        initListView()

        isDeviceConnecting = TempData.getDeviceConnectState()
        connectDeviceAddress = TempData.getConnectDeviceMac()
        mListBluetoothDevices.addAll(TempData.getHistoryDevices())
        mBluetoothAdapter?.notifyDataSetChanged()
    }

    @SuppressLint("SetTextI18n")
    private fun initListView() {
        val view = LayoutInflater.from(context).inflate(R.layout.layout_bluetooth_device, this, true)
        mRecyclerViewBluetooth = view.findViewById(R.id.mRecyclerViewDevices)

        val llm = LinearLayoutManager(context)
        mRecyclerViewBluetooth?.layoutManager = llm
        mBluetoothAdapter = YDSRecyclerViewOAdapter<BluetoothDevice>(context, R.layout.adapter_bluetooth_item, mListBluetoothDevices)
        mBluetoothAdapter?.setItemDatasListener(YDSRecyclerViewOAdapter.ItemDatasListener { holder: CommonViewHolder, bluetoothDevice: BluetoothDevice, _: Int ->
            val mClContainerBluetooth = holder.getView<LinearLayoutCompat>(R.id.mClContainerBluetooth)
            val mTvBluetoothName = holder.getView<TextView>(R.id.mTvBluetoothName)
            val mTvBluetoothMac = holder.getView<TextView>(R.id.mTvBluetoothMac)
            val mVSplit = holder.getView<View>(R.id.mVSplit)

            // 蓝牙名称
            mTvBluetoothName.setTextColor(bluetoothDeviceNameColor)
            mTvBluetoothName.textSize = bluetoothDeviceNameSize
            mTvBluetoothName.text = bluetoothDeviceNameAppend + bluetoothDevice.name
            if (isDeviceConnecting && connectDeviceAddress == bluetoothDevice.address) {
                mTvBluetoothName.text = bluetoothDeviceNameAppend + bluetoothDevice.name + resources.getString(R.string.str_already_connect)
            }
            // 背景色
            if (null != selectedDevice && selectedDevice?.address == bluetoothDevice.address) {
                mClContainerBluetooth.setBackgroundColor(bluetoothDeviceSelectedBackground)
            } else {
                mClContainerBluetooth.setBackgroundColor(bluetoothDeviceDefaultBackground)
            }
            // 蓝牙mac地址
            mTvBluetoothMac.setTextColor(bluetoothDeviceMacColor)
            mTvBluetoothMac.textSize = bluetoothDeviceMacSize
            when (bluetoothDevice.type) {
                BluetoothDevice.DEVICE_TYPE_CLASSIC -> mTvBluetoothMac.text =
                    bluetoothDeviceMacAppend + bluetoothDevice.address + if (bluetoothDeviceTypeVisible) resources.getString(R.string.str_classic_device) else ""
                BluetoothDevice.DEVICE_TYPE_LE -> mTvBluetoothMac.text =
                    bluetoothDeviceMacAppend + bluetoothDevice.address + if (bluetoothDeviceTypeVisible) resources.getString(R.string.str_low_power_device) else ""
                BluetoothDevice.DEVICE_TYPE_DUAL -> mTvBluetoothMac.text =
                    bluetoothDeviceMacAppend + bluetoothDevice.address + if (bluetoothDeviceTypeVisible) resources.getString(R.string.str_compatible_device) else ""
            }
            // 分割线是否可见
            mVSplit.visibility = if (bluetoothDeviceSplitLineVisible) View.VISIBLE else View.INVISIBLE
            if (bluetoothDeviceSplitLineHeight != -1) {
                val layoutParams = mVSplit.layoutParams
                layoutParams.height = bluetoothDeviceSplitLineHeight
                mVSplit.layoutParams = layoutParams
            }
        } as YDSRecyclerViewOAdapter.ItemDatasListener<BluetoothDevice>)

        mRecyclerViewBluetooth?.adapter = mBluetoothAdapter
        mBluetoothAdapter?.setOnItemClickListener(object : YDSRecyclerViewOAdapter.OnItemClickListener {
            override fun setOnItemClickListener(view: View, position: Int) {
                selectedDevice = mListBluetoothDevices[position]
                mBluetoothAdapter?.notifyDataSetChanged()
                Log.i(tag, "setOnItemClickListener: = $position")
            }

            override fun setOnItemLongClickListener(view: View, position: Int) {}
        })
    }

    override fun onScanDeviceStart(autoStop: Boolean, showAnim: Boolean, nameCanEmpty: Boolean, scanBleOnly: Boolean) {
        mListBluetoothDevices.clear()
        // 如果正在连接状态，断开连接后再尝试连接新设备。
        if (isDeviceConnecting) {
            onDisconnectFromBluetoothDevice()
        }

        val scanDevice = YDSBluetoothHelper.scanBluetoothDevice(true, showAnim, nameCanEmpty, scanBleOnly) {
            mListBluetoothDevices.add(it)
            mBluetoothAdapter?.notifyDataSetChanged()
        }
        if (!scanDevice) {
//            YDSBluetoothHelper.requestPermission(1)
            return
        }
        // 如果设置自动停止，5秒后执行。
        if (autoStop) {
            YDSDelayHelper.delay(5000) {
                YDSBluetoothHelper.scanBluetoothDevice(false, showAnim, nameCanEmpty, scanBleOnly) {}
            }
        }
    }

    override fun onScanDeviceStop() {
        YDSBluetoothHelper.scanBluetoothDevice(false) {}
    }

    override fun onConnectStateChanged(enable: Boolean) {
        Log.i(tag, "onConnectStateChanged: $enable")
        isDeviceConnecting = enable
        mBluetoothAdapter?.notifyDataSetChanged()
    }

    override fun onConnectToBluetoothDevice(resultCallback: (Boolean, BluetoothDevice) -> Unit) {
        selectedDevice?.let {
            YDSBluetoothHelper.connectToBluetoothDevice(it) { connectState ->
                isDeviceConnecting = connectState
                if (connectState) {
                    connectDeviceAddress = selectedDevice?.address.toString()
                    TempData.setConnectDeviceMac(connectDeviceAddress)
                    mRecyclerViewBluetooth?.post {
                        mBluetoothAdapter?.notifyDataSetChanged()
                    }
                }
                TempData.setDeviceConnectState(connectState)
                TempData.putDevices(mListBluetoothDevices)

                selectedDevice?.let {
                    resultCallback.invoke(connectState, it)
                }
            }
        }
    }

    override fun sendDataToBluetoothDevice(data: ByteArray, sendResultCallback: (Boolean) -> Unit, receiveResultCallback: (ByteArray) -> Unit) {
        YDSBluetoothHelper.sendDataToBluetoothDevice(data, sendResultCallback, receiveResultCallback)
    }

    override fun onDisconnectFromBluetoothDevice() {
        YDSBluetoothHelper.disconnectFromBluetoothDevice()
        isDeviceConnecting = false
        mBluetoothAdapter?.notifyDataSetChanged()
    }

    private var bluetoothDeviceTypeVisible = true
    override fun onBluetoothDeviceTypeVisible(visible: Boolean) {
        bluetoothDeviceTypeVisible = visible
    }

    private var bluetoothDeviceDefaultBackground = Color.WHITE
    override fun onBluetoothDeviceDefaultBackground(colorId: Int) {
        bluetoothDeviceDefaultBackground = colorId
    }

    private var bluetoothDeviceSelectedBackground = Color.parseColor("#999999")
    override fun onBluetoothDeviceSelectedBackground(colorId: Int) {
        bluetoothDeviceSelectedBackground = colorId
    }

    private var bluetoothDeviceSplitLineVisible = true
    override fun onBluetoothDeviceSplitLineVisible(visible: Boolean) {
        bluetoothDeviceSplitLineVisible = visible
    }

    private var bluetoothDeviceSplitLineHeight = -1
    override fun onBluetoothDeviceSplitLineHeight(height: Int) {
        bluetoothDeviceSplitLineHeight = height
    }

    private var bluetoothDeviceNameAppend = ""
    override fun onBluetoothDeviceNameAppend(msg: String) {
        bluetoothDeviceNameAppend = msg
    }

    private var bluetoothDeviceNameColor = Color.parseColor("#333333")
    override fun onBluetoothDeviceNameColor(colorId: Int) {
        bluetoothDeviceNameColor = colorId
    }

    private var bluetoothDeviceNameSize = 18f
    override fun onBluetoothDeviceNameSize(size: Float) {
        bluetoothDeviceNameSize = size
    }

    private var bluetoothDeviceMacAppend = ""
    override fun onBluetoothDeviceMacAppend(msg: String) {
        bluetoothDeviceMacAppend = msg
    }

    private var bluetoothDeviceMacColor = Color.parseColor("#666666")
    override fun onBluetoothDeviceMacColor(colorId: Int) {
        bluetoothDeviceMacColor = colorId
    }

    private var bluetoothDeviceMacSize = 14f
    override fun onBluetoothDeviceMacSize(size: Float) {
        bluetoothDeviceMacSize = size
    }
}